package com.cong.leetcode._32;
import java.util.LinkedList;
import java.util.Stack;
public class Solution {
    public int longestValidParentheses(String s) {
        if (s == null) return 0;
        int len = s.length();
        if (0 == len) return 0;
        char[] chars = s.toCharArray();

        Stack<Integer> plStack = new Stack<>();
        int maxLen = 0;
        int lastConnectableRightBound = -1;
        int lastConnectableLen = 0;
        boolean broken = true;
        LinkedList<Integer> l = null;


        for (int i = 0;i < len; i++) {
            int c = chars[i];
            if (c == '(') {
                plStack.push(i);
//                if (broken) {
//                    lastConnectableRightBound = -1;
//                    broken = false;
//                }
                continue;
            }
            if (c == ')') {
                if (plStack.size() == 0)  {
                    continue;
                }else {
                    int curLeft = plStack.pop();

                    int curLeftBound = plStack.size() > 0 ? plStack.peek() : curLeft - 1 ;
                    int curLen = i -  curLeftBound;
                    if (curLeftBound == lastConnectableRightBound) {
                        curLen += lastConnectableLen;
                        lastConnectableLen = curLen;
                        lastConnectableRightBound = i;
                    }
                    if (plStack.size() == 0) {
                        lastConnectableRightBound = i;
                        lastConnectableLen = curLen;
                    }

                    maxLen = Math.max(maxLen, curLen);

                }
                continue;
            }
            return -1;
        }
        return maxLen;
    }
}
